{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<font color=\"#a9a56c\" size=2> **@Author: Arif Kasim Rozani - (Team Operation Badar)** </font>"
      ],
      "metadata": {
        "id": "38_QpUXJOAII"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "#File Handling in Python: A Comprehensive Tutorial with Examples\n",
        "\n",
        "File handling is essential for reading and writing data to files, enabling persistent storage. Python provides built-in functions and methods to handle files efficiently. This tutorial covers the fundamentals with examples.\n",
        "\n",
        "---------\n",
        "\n",
        "\n",
        "1. Opening a File\n",
        "  \n",
        "  Use the open() function to open a file. Specify the mode (read, write, append, etc.).\n",
        "\n",
        "\n",
        "* Modes:\n",
        "\n",
        "  * r: Read (default)\n",
        "\n",
        "  * w: Write (Opens the file for writing. Creates the file if it doesn't exist, or overwrites it if it does.)\n",
        "\n",
        "  * a: Append (Opens the file for appending. Creates the file if it doesn't exist, or adds to it if it does.)\n",
        "\n",
        "  * x: Exclusive creation (fails if file exists)\n",
        "\n",
        "  * b: Binary mode (Used with the other modes (e.g., \"rb\", \"wb\") for working with binary files.)\n",
        "\n",
        "  * +: Update mode (Can be combined with other modes (e.g., \"r+\", \"w+\") to allow both reading and writing.)\n",
        "<br>\n",
        "------------------\n",
        "<br>\n",
        "\n",
        "###OK, Let's create a file in Colab.\n",
        "\n",
        "<br>\n",
        "\n",
        "**`w: Write mode`**. Opens the file for writing. Creates the file if it doesn't exist, or overwrites it if it does."
      ],
      "metadata": {
        "id": "U4O62nD57bIt"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file = open(\"new_file.txt\", \"w\")"
      ],
      "metadata": {
        "id": "RkOEWcpAGYPq"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "###Writing to Files:\n",
        "\n",
        "To write to a file, open it in write (\"w\") or append (\"a\") mode.\n",
        "\n",
        "write(string): Writes the given string to the file."
      ],
      "metadata": {
        "id": "ptU9D4FfHsOZ"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "fFKCzAIf6io9"
      },
      "outputs": [],
      "source": [
        "file.write(\"Hello, world!\\n\")  # \\n creates a new line\n",
        "file.write(\"This is another line.\\n\")\n",
        "file.close()"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "writelines(list): Writes a list of strings to the file."
      ],
      "metadata": {
        "id": "pZo2KjI6IAFw"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "lines = [\"Line 1: Karachi\\n\", \"Line 2: Lahore\\n\", \"Line 3: Peshawar\\n\"]\n",
        "file = open(\"new_file.txt\", \"a\") # run with mode w, and see the result\n",
        "file.writelines(lines)\n",
        "file.close()"
      ],
      "metadata": {
        "id": "nPshU4pNID5Y"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#### Uptill now we have created a file with 'w' & 'a' mode and also write some lines in it.\n",
        "\n",
        "#### Now let start reading the file what we have created earlier."
      ],
      "metadata": {
        "id": "rGH0IR90I-EH"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Run the below line of code and see the error 😞\n",
        "\n",
        "Explain why?"
      ],
      "metadata": {
        "id": "Mw_Efs3DKMrA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file = open(\"my_file.txt\", \"r\")  # Opens \"my_file.txt\" in read mode (\"r\")"
      ],
      "metadata": {
        "id": "2GRRmp7OJmwf"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "So lets correct the name of the file 😀"
      ],
      "metadata": {
        "id": "rv4GOx2_Khu9"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file = open(\"new_file.txt\", \"r\")  # Opens \"my_file.txt\" in read mode (\"r\")"
      ],
      "metadata": {
        "id": "BesydjN0KZnt"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "content = file.read()\n",
        "print(content)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "TprZH2EJJw7m",
        "outputId": "a67296f6-e948-4257-8488-6de6f160442a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karachi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "line = file.readline()\n",
        "print(line)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "WjK-5IzdUPDP",
        "outputId": "37dd2450-304b-4a56-a43a-9bf43d540ad8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "####Nothing Printed ☹\n",
        "\n",
        "###Here you need to know the concept of file pointer\n",
        "\n",
        "---------\n",
        "\n",
        "In Python, a `file pointer` (also called a `file cursor` or `file position indicator`) is an internal marker that keeps track of the `current position` in a file where the next read or write operation will occur. When you open a file, the file pointer is initialized to a specific position (`usually 0, the beginning of the file`), and it moves automatically as you read from or write to the file.\n",
        "\n",
        "<br>\n",
        "\n",
        "Key Concepts:\n",
        "1. Starting Position:\n",
        "  * r (read mode): Pointer starts at 0 (beginning of the file).\n",
        "  * a (append mode): Pointer starts at the end of the file.\n",
        "  * w (write mode): The file is truncated (erased), and the pointer starts at 0.\n",
        "\n",
        "2. How It Moves:\n",
        "  * When you read/write data, the pointer moves forward by the number of bytes/characters processed.\n",
        "  * Example: Reading 10 characters moves the pointer 10 positions forward.\n",
        "\n",
        "3. Manual Control:\n",
        "  * Use seek(offset) to move the pointer to a specific byte position.\n",
        "  * Use tell() to check the current pointer position."
      ],
      "metadata": {
        "id": "-c5gybV9XCML"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "###Move pointer back to start."
      ],
      "metadata": {
        "id": "bBmv01OEZ37C"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file.seek(0)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "6eA8yFsXZcgB",
        "outputId": "9f89d186-d4d0-4ce0-a543-562b6099cbe1"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "0"
            ]
          },
          "metadata": {},
          "execution_count": 39
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "###Check the file cursor/pointer position after running seek(0) method."
      ],
      "metadata": {
        "id": "PEJh0xZJaSPQ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(\"Position after seek(0):\", file.tell())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "aRM8WZKIaI4K",
        "outputId": "2fcf37f7-80e6-4418-b231-493b925d42f6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Position after seek(0): 0\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "line = file.readline()\n",
        "print(line)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "JqtaayV0amfo",
        "outputId": "82597be8-8a51-4833-da24-8090d657f0eb"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Line 1: Karchi\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### readlines(): Reads all lines into a list."
      ],
      "metadata": {
        "id": "isC3k3BAbOvI"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file.seek(0) # First move the pointer to the start\n",
        "\n",
        "lines = file.readlines()\n",
        "for line in lines:\n",
        "    print(line)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "pIVxn3Q7bVwP",
        "outputId": "bd9c9f17-6de9-4865-d3bf-123b0e876023"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Line 1: Karchi\n",
            "\n",
            "Line 2: Lahore\n",
            "\n",
            "Line 3: Peshawar\n",
            "\n",
            "Line 1: Karchi\n",
            "\n",
            "Line 2: Lahore\n",
            "\n",
            "Line 3: Peshawar\n",
            "\n",
            "Line 1: Karachi\n",
            "\n",
            "Line 2: Lahore\n",
            "\n",
            "Line 3: Peshawar\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "file = open(\"new_file.txt\", \"r\")\n",
        "for line in file:  # Iterating directly over the file reads line by line\n",
        "    print(line.strip()) # .strip() removes leading/trailing whitespace"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "eGbq_oqYcEUf",
        "outputId": "b109338a-d8f4-4966-a4ba-d42cce423271"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karachi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Closing Files:\n",
        "\n",
        "* It's crucial to close files after you're finished with them.  This releases system resources and ensures that data is properly written to the disk.  The `close()` method is used for this:"
      ],
      "metadata": {
        "id": "6aC-xmhKcpT-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file.close()"
      ],
      "metadata": {
        "id": "V_pdojkeccNG"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Additional Tips\n",
        "- Exclusive Creation (x mode):\n",
        "\n",
        "### Best Practices:\n",
        "- Use `with` for automatic cleanup.\n",
        "- Handle exceptions to avoid crashes."
      ],
      "metadata": {
        "id": "EpPES2W4dZxA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "try:\n",
        "    with open('unique.txt', 'x') as file:\n",
        "        file.write('Created exclusively!')\n",
        "except FileExistsError:\n",
        "    print(\"File already exists.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "48RhV8tMdjD9",
        "outputId": "2629cfad-78f4-4b8c-c41f-afb97418af53"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "File already exists.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "### The `with` Statement (Context Manager):\n",
        "\n",
        "- The best practice for file handling is to use the `with` statement.  This ensures that the file is `automatically closed, even if errors occur`."
      ],
      "metadata": {
        "id": "uctnN03Ed9k1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "with open(\"new_file.txt\", \"r\") as file:\n",
        "    content = file.read()\n",
        "    print(content)\n",
        "# File is automatically closed here"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VOynBzbOeLY0",
        "outputId": "ac9c6e47-1536-45da-eddd-146ed7f1439f"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karchi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "Line 1: Karachi\n",
            "Line 2: Lahore\n",
            "Line 3: Peshawar\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The above cell use the `with` statement which close the file after use, let's validate it."
      ],
      "metadata": {
        "id": "W3vYewaZedBk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "file.tell() # will produce error, file is already closed because of with statement"
      ],
      "metadata": {
        "id": "IQWpdkk0eTIs"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Example: Copying a file"
      ],
      "metadata": {
        "id": "hK7C3KechVYz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def copy_file(source_path, destination_path):\n",
        "    try:\n",
        "        with open(source_path, \"r\") as source_file, open(destination_path, \"w\") as dest_file:\n",
        "            for line in source_file:\n",
        "                dest_file.write(line)\n",
        "        print(f\"File '{source_path}' copied to '{destination_path}' successfully.\")\n",
        "    except FileNotFoundError:\n",
        "        print(f\"Error: Source file '{source_path}' not found.\")\n",
        "    except Exception as e:\n",
        "        print(f\"An error occurred: {e}\")\n",
        "\n",
        "copy_file(\"unique.txt\", \"unique_copy.txt\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Fs2Kw0PGg6Hj",
        "outputId": "17ec3976-a5c8-496d-8bd9-5a874cfed44d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "File 'unique.txt' copied to 'unique_copy.txt' successfully.\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Full Example: File Operations Demo"
      ],
      "metadata": {
        "id": "dKGW7JOqhjEB"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Create and write to a file\n",
        "with open('demo.txt', 'w') as file:\n",
        "    file.write('Python File Handling\\n')\n",
        "    file.write('Line 1\\nLine 2\\n')\n",
        "\n",
        "# Read and print content\n",
        "with open('demo.txt', 'r') as file:\n",
        "    print(\"Content:\")\n",
        "    print(file.read())\n",
        "\n",
        "# Append a new line\n",
        "with open('demo.txt', 'a') as file:\n",
        "    file.write('Appended line\\n')\n",
        "\n",
        "# Read lines using seek\n",
        "with open('demo.txt', 'r+') as file:\n",
        "    file.seek(0)\n",
        "    print(\"First line:\", file.readline())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rIj96znFhlUK",
        "outputId": "864318d9-d312-4745-a898-b379fbf4f27d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Content:\n",
            "Python File Handling\n",
            "Line 1\n",
            "Line 2\n",
            "\n",
            "First line: Python File Handling\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Conclusion\n",
        "- Python’s file handling is straightforward with **`open(), read(), write(), and close()`**. Always use the **`with`** statement for safety and leverage exception handling for robustness. Experiment with modes and methods to manage files effectively!"
      ],
      "metadata": {
        "id": "MqQpqp2uhxcC"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# prompt: generate a comprehensive example of file handling using all the functions\n",
        "\n",
        "# Create a file and write to it\n",
        "with open('example.txt', 'w') as f:\n",
        "  f.write(\"This is line 1.\\n\")\n",
        "  f.write(\"This is line 2.\\n\")\n",
        "  f.writelines([\"This is line 3.\\n\", \"This is line 4.\\n\"])\n",
        "\n",
        "# Read the file and print its content\n",
        "with open('example.txt', 'r') as f:\n",
        "  content = f.read()\n",
        "  print(\"--- Full Content ---\")\n",
        "  print(content)\n",
        "\n",
        "# Read the file line by line and print each line\n",
        "with open('example.txt', 'r') as f:\n",
        "  print(\"--- Line by Line ---\")\n",
        "  for line in f:\n",
        "    print(line, end='')\n",
        "\n",
        "# Read a single line\n",
        "with open('example.txt', 'r') as f:\n",
        "  print(\"\\n--- Readline ---\")\n",
        "  print(f.readline(), end='')\n",
        "\n",
        "# Read all lines into a list\n",
        "with open('example.txt', 'r') as f:\n",
        "  lines = f.readlines()\n",
        "  print(\"\\n--- Readlines ---\")\n",
        "  for line in lines:\n",
        "    print(line, end='')\n",
        "\n",
        "# Append to the file\n",
        "with open('example.txt', 'a') as f:\n",
        "  f.write(\"This is appended line 1.\\n\")\n",
        "  f.write(\"This is appended line 2.\\n\")\n",
        "\n",
        "# Reading with seek and tell\n",
        "with open('example.txt', 'r') as f:\n",
        "  print(\"\\n--- Seek and Tell ---\")\n",
        "  print(\"Current position:\", f.tell())\n",
        "  print(\"First line:\", f.readline(), end=\"\")\n",
        "  print(\"Current position:\", f.tell())\n",
        "  f.seek(0)\n",
        "  print(\"After seek(0):\", f.tell())\n",
        "  print(\"First line again:\", f.readline(), end=\"\")\n",
        "\n",
        "# Demonstrating 'x' mode (exclusive creation)\n",
        "try:\n",
        "    with open('new_file.txt', 'x') as f:\n",
        "        f.write(\"This is a new file created in 'x' mode.\")\n",
        "        print(\"new_file.txt created successfully!\")\n",
        "except FileExistsError:\n",
        "    print(\"File 'new_file.txt' already exists!\")\n",
        "\n",
        "# Copy file example\n",
        "def copy_file(source, destination):\n",
        "  try:\n",
        "    with open(source, 'r') as src, open(destination, 'w') as dest:\n",
        "      for line in src:\n",
        "        dest.write(line)\n",
        "      print(f\"'{source}' successfully copied to '{destination}'\")\n",
        "  except FileNotFoundError:\n",
        "    print(f\"Error: File not found '{source}'\")\n",
        "  except Exception as e:\n",
        "    print(f\"Error during copying: {e}\")\n",
        "\n",
        "copy_file(\"example.txt\", \"example_copy.txt\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "N2ouSgeU7zTW",
        "outputId": "21f077fa-5ffd-460b-b621-ee0067ece149"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "--- Full Content ---\n",
            "This is line 1.\n",
            "This is line 2.\n",
            "This is line 3.\n",
            "This is line 4.\n",
            "\n",
            "--- Line by Line ---\n",
            "This is line 1.\n",
            "This is line 2.\n",
            "This is line 3.\n",
            "This is line 4.\n",
            "\n",
            "--- Readline ---\n",
            "This is line 1.\n",
            "\n",
            "--- Readlines ---\n",
            "This is line 1.\n",
            "This is line 2.\n",
            "This is line 3.\n",
            "This is line 4.\n",
            "\n",
            "--- Seek and Tell ---\n",
            "Current position: 0\n",
            "First line: This is line 1.\n",
            "Current position: 16\n",
            "After seek(0): 0\n",
            "First line again: This is line 1.\n",
            "new_file.txt created successfully!\n",
            "'example.txt' successfully copied to 'example_copy.txt'\n"
          ]
        }
      ]
    }
  ]
}